package com.tv.cms.system.login;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.tv.cms.system.account.model.Account;
import com.tv.cms.system.account.service.AccountService;
import com.tv.cms.system.admin.model.Admin;
import com.tv.cms.system.admin.service.AdminService;
import com.tv.cms.system.menu.model.Menu;
import com.tv.cms.system.menu.service.MenuService;
import com.tv.cms.system.permission.model.Permission;
import com.tv.cms.system.permission.service.PermissionService;
import com.tv.cms.system.role.model.Role;
import com.tv.cms.utils.HttpRequestUtils;
import com.tv.cms.utils.Md5encrypt;
import com.tv.cms.utils.Result;
import com.tv.cms.utils.ResultCode;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * TODO
 *  登录
 * @author
 * @date
 **/
@RestController
@RequestMapping("system")
public class LoginController {

    @Resource
    private AdminService service;
    @Resource
    private PermissionService permissionService;
    @Resource
    private MenuService menuService;

    /**
     * 登录
     */
    @PostMapping("login")
    public Result login(@RequestBody Admin admin, HttpServletRequest request){
        Admin one = service.getOne(new QueryWrapper<Admin>().eq("user_name", admin.getUserName()).eq("password", Md5encrypt.getMD5Str(admin.getPassword())).eq("status",1));
        if(one != null){


            String ipAddr = HttpRequestUtils.getIpAddr(request);
            one.setLoginIp(ipAddr);
            one.setLoginDate(new Date());
            service.updateById(one);

            StpUtil.login(one.getId());
            SaTokenInfo saTokenInfo = StpUtil.getTokenInfo();
            String token = saTokenInfo.getTokenValue();
            long tokenTimeout = saTokenInfo.getTokenTimeout();
            one.setPassword("");
            Map<Object, Object> res = new HashMap<>();
            res.put("token", token);
            res.put("tokenTimeout", tokenTimeout);
            res.put("info", one);

            return new Result<>(ResultCode.SUCCESS.getCode(),ResultCode.SUCCESS.getMsg(),res);
        }else{
            // 登录失败，返回错误信息
            return new Result<>(ResultCode.FAILURE.getCode(),"用户名或密码不正确",null);
        }

    }

    /**
     * 登录后得到用户信息
     * @return
     */
    @GetMapping("info")
    public Result<Map<String, Object>> authInfo(){

        MPJLambdaWrapper<Admin> wrapper = new MPJLambdaWrapper<Admin>()
                .selectAll(Admin.class)
                .selectAs(Role :: getName,Admin :: getRoleName)
                .selectAs(Role :: getType,"roleType")
                .selectAs(Role :: getId,"roleId")
                .leftJoin(Role.class, Role::getId, Admin::getRoleId)
                .eq(Admin :: getId,StpUtil.getLoginIdAsInt());
        Map<String, Object> map = service.selectJoinMap(wrapper);
        Object roleName = map.get("roleName");
        if(!Objects.isNull(roleName)){
            map.put("roles",new ArrayList<>(Arrays.asList(roleName.toString())));
            Object roleId = map.get("roleId");
            List<String> permissions = new ArrayList<>();
           // if(roleId.toString().equals("1")){
                List<Menu> menuList = menuService.list(new QueryWrapper<Menu>().eq("status",1));
                for (Menu menu : menuList) {
                    permissions.add(menu.getItem());
                }
           /* }else{
                List<Permission> permissionList = permissionService.list(new QueryWrapper<Permission>().eq("role_id", map.get("roleId")).eq("status", 1));
                for (Permission permission : permissionList) {
                    permissions.add(permission.getItem());
                }
            }*/

            map.put("permissions",permissions);
            map.put("roleId",roleId);
            map.put("userId",StpUtil.getLoginIdAsInt());
        }
        map.put("roleType",Integer.parseInt( map.get("roleType").toString() ));
        return new Result<>(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMsg(),map);
    }

    /**
     * 登出
     */
    @PostMapping("logout")
    public Result<String> logout(){
        StpUtil.logout();
       /* SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        if(tokenInfo != null){
            StpUtil.kickoutByTokenValue(tokenInfo.getTokenValue());
        }*/
        return new Result<>(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMsg(),"登出成功");
    }

}
